const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g; // 匹配 {{}} 表达式
export function generate(ast) {
  let code = `_c('${ast.tag}'`;
  code += ",";
  code += ast.attrs.length > 0 ? genAttrs(ast.attrs) : "null";

  code += ast.children.length > 0 ? `,${genChildren(ast.children)}` : "";

  return code;
}

function genAttrs(attrs) {
  let code = "";
  for (let i = 0; i < attrs.length; i++) {
    let attr = attrs[i];
    if (attr.name == "style") {
      let obj = {};
      attr.value.split(";").forEach((item) => {
        let [key, value] = item.split(":");
        obj[key] = value;
      });
      attr.value = obj;
    }
    code += `${attr.name}:${JSON.stringify(attr.value)},`;
  }
  // 去掉最后一个逗号
  return `{${code.slice(0, -1)}}`;
}

function genChildren(children) {
  return children.map((child) => gen(child)).join(",");
}
function gen(node) {
  if (node.type == 1) {
    return generate(node);
  } else {
    let text = node.text;
    if (!defaultTagRE.test(text)) {
      return `_v(${JSON.stringify(text)})`;
    }
    let tokens = [];
    let match;
    defaultTagRE.lastIndex = 0; // 重置正则表达式的 lastIndex 属性，确保从字符串开头开始匹配
    let lastIndex = 0;
    while ((match = defaultTagRE.exec(text))) {
      let index = match.index;
      if (index > lastIndex) {
        tokens.push(JSON.stringify(text.slice(lastIndex, index)));
      }

      tokens.push(`_s(${match[1].trim()})`);
      lastIndex = index + match[0].length;
    }
    if (lastIndex < text.length) {
      tokens.push(JSON.stringify(text.slice(lastIndex)));
    }
    return `_v(${tokens.join("+")})`;
  }
}
